package com.mhfelipe.applet.print;

import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.JobName;
import java.awt.print.PrinterJob;
import java.io.ByteArrayInputStream;
import java.util.Locale;

public class PrintByPool extends AbstractPrint {

    public void start() {

        int iCHR27Val = 27;
        char cCHR27 = (char) iCHR27Val;
        int iCHR4Val = 4;
        char cCHR4 = (char) iCHR4Val;

        StringBuilder toPrint = new StringBuilder()
                .append(cCHR27)
                .append("c0")
                .append(cCHR4)
                .append(getContent());

        String jobName = getParameter("jobName");
        String printerName = getParameter("printerName");

        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(new JobName(jobName == null ? "Applet Print" : jobName, new Locale("pt", "BR")));

        PrintService printer = null;
        PrintService[] lookupPrintServices = PrinterJob.lookupPrintServices();
        if (lookupPrintServices.length == 0) {
            return;
        } else if (lookupPrintServices.length == 1) {
            printer = lookupPrintServices[0];
        } else {
            if (printerName != null) {
                for (PrintService p : lookupPrintServices) {
                    if (p.getName().equalsIgnoreCase(printerName)) {
                        printer = p;
                        break;
                    }
                }
            }
        }

        if (printer == null) {
            printer = PrinterJob.getPrinterJob().getPrintService();
        }

        try {
            DocPrintJob docPrint = printer.createPrintJob();
            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
            Doc doc = new SimpleDoc(new ByteArrayInputStream(toPrint.toString().getBytes()), flavor, null);
            docPrint.print(doc, aset);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
